import 'dart:collection';

import 'package:get/get.dart';

import '../../../lib_basemodel/chat_room/flyScreen/flying_data.dart';
import '../../animated/animated.dart';
import '../../utils/screen_utils.dart';

class FloatScreenController extends GetxController {
  // 飘屏数据队列
  final Queue<FlyingData> _queue = Queue();
  // 当前飘屏数据
  FlyingData? _current;

  // 动画顺序集合
  Sequence? _sequence;
  late ValueAnimation _trx;

  @override
  void onInit() {
    super.onInit();
    _trx = Animated.value(ScreenUtils.ins.screenWidth);
  }

  @override
  void onReady() {
    super.onReady();
    _initAnim();
  }

  @override
  void onClose() {
    _sequence?.stop();
    _sequence?.dispose();
    _sequence = null;
    super.onClose();
  }

  FlyingData? get data => _current;

  double get trx => _trx.value;

  void _initAnim() {
    _sequence?.stop();
    _sequence = Animated.sequence([
      Animated.spring(
        _trx,
        toValue: 0.0,
        speed: 1.0,
        bounciness: 3.0,
      ),
      Animated.delay(const Duration(milliseconds: 2000)),
      Animated.spring(_trx,
          toValue: 0 - ScreenUtils.ins.screenWidth,
          speed: 3.0,
          bounciness: 3.0,
          overshootClamping: true),
    ], _onAniUpdate);
    _sequence?.start();
  }

  void _onAniUpdate(bool complete) {
    if (complete) {
      _handleNext();
    } else {
      update(['trx']);
    }
  }

  void _handleNext() {
    _current = null;
    _sequence?.stop();
    update();
    if (_queue.isNotEmpty) {
      _current = _queue.removeFirst();
      _trx.reset();
      update();
      if (_sequence == null) {
        _initAnim();
      } else {
        _sequence?.start();
      }
    } else {
      _trx.reset();
      _sequence = null;
    }
  }

  void push(FlyingData data) {
    _queue.add(data);
    _current ??= _queue.removeFirst();
    if (initialized && _sequence == null) {
      update();
      _initAnim();
    }
  }
}
